package com.cavy.platform.server.service;

import com.cavy.platform.server.domain.AbstractConfigMap;
import com.cavy.platform.server.domain.FileConfigMap;
import com.cavy.platform.server.dto.AbstractConfigMapCreateDto;
import com.cavy.platform.server.repository.ConfigMapRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Service
public class ConfigMapService {
    @Autowired
    private ConfigMapRepository repository;

    public void create(AbstractConfigMapCreateDto dto) {
        AbstractConfigMap abstractConfigMap = dto.getMapType().getFactory().create();
        dto.setValue(abstractConfigMap);
        abstractConfigMap.save();
    }

    public AbstractConfigMap info(String workspace, String name) {
        return repository.load(workspace, name);
    }

    public List<AbstractConfigMap> list(String workspace, String key) {
        return repository.list(workspace, key);
    }

    public void getValue(String workspace, String name, HttpServletResponse response) {
        AbstractConfigMap load = repository.load(workspace, name);
        load.getValue(response);
    }

    public void upload(MultipartFile file, String workspace, String name) {
        AbstractConfigMap load = repository.load(workspace, name);
        if (load instanceof FileConfigMap) {
            FileConfigMap fileMap = (FileConfigMap) load;
            fileMap.setFileName(file.getOriginalFilename());
            try {
                file.transferTo(fileMap.getFile());
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                fileMap.save();
            }
        }
    }

    public void delete(String workspace, String name) {
        AbstractConfigMap load = repository.load(workspace, name);
        load.delete();
    }
}
